package com.fate.securecheckplatform.utils;

import android.annotation.SuppressLint;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.os.Environment;
import android.view.View;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;

/**
 * 文件工具类
 */
public class FileUtil {
    private static final long B = 1;
    private static final long KB = B * 1024;
    private static final long MB = KB * 1024;
    private static final long GB = MB * 1024;

    /**
     * 判断是否有SD卡
     *
     * @return boolean
     */
    public static boolean hasSDCard() {
        String status = Environment.getExternalStorageState();
        if (!status.equals(Environment.MEDIA_MOUNTED)) {
            return false;
        }
        return true;
    }

    /**
     * 建立保存头像的路径及名称
     */

    public static File saveOutputMediaFile(String mImageName) {
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/SecureCheckPlatform/images/");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            } else mediaStorageDir.mkdirs();
        }
        File mediaFile;
        // 设置图片名字
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName + ".jpg");
        return mediaFile;
    }

    public static String getSaveImagePath() {
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/SecureCheckPlatform/images/");
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            } else mediaStorageDir.mkdirs();
        }
        return mediaStorageDir.getAbsolutePath();
    }


    /**
     * 获取文件夹下的所有图片路径
     *
     * @param fileDir
     * @return
     */
    public static File[] getImageFiles(String fileDir) {
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory() + "/SecureCheckPlatform/images/" + fileDir);
        File[] listFiles = new File[0];
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        } else {
            listFiles = mediaStorageDir.listFiles();
        }
        return listFiles;
    }

    /**
     * 以流的形式保存拍照的图片到指定文件夹
     *
     * @param bitmap     要保存的图片
     * @param mImageName 要保存的文件名称
     */
    public static void saveBitmap2SD(Bitmap bitmap, String mImageName) {
        FileOutputStream fos = null;
        File bitmapFile = saveOutputMediaFile(mImageName);
        if (bitmapFile == null) {
            return;
        }
        try {
            fos = new FileOutputStream(bitmapFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    public static String saveBitmap2File(Bitmap bitmap, String mImageName) {
        FileOutputStream fos = null;
        File bitmapFile = saveOutputMediaFile(mImageName);
        if (bitmapFile == null) {
            return "";
        }
        try {
            fos = new FileOutputStream(bitmapFile);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 75, fos);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (fos != null) {
                    fos.flush();
                    fos.close();
                }

            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return bitmapFile.getAbsolutePath();
    }

    /**
     * 把指定的View 保存为图片
     *
     * @param view
     */
    public static String viewSaveToImage(View view, String name) {
        view.setDrawingCacheEnabled(true);
        view.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_HIGH);
        view.setDrawingCacheBackgroundColor(Color.WHITE);

        // 把一个View转换成图片
        Bitmap cachebmp = loadBitmapFromView(view);

        FileOutputStream fos;
        String imagePath = "";
        try {
            // 判断手机设备是否有SD卡
            boolean isHasSDCard = Environment.getExternalStorageState().equals(
                    android.os.Environment.MEDIA_MOUNTED);
            if (isHasSDCard) {
                // SD卡根目录
                File sdRoot = Environment.getExternalStorageDirectory();
                File file = new File(sdRoot, name + ".png");
                fos = new FileOutputStream(file);
                imagePath = file.getAbsolutePath();
            } else
                throw new Exception("创建文件失败!");

            cachebmp.compress(Bitmap.CompressFormat.PNG, 90, fos);

            fos.flush();
            fos.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
        LogUtil.e("imagePath=" + imagePath);

        view.destroyDrawingCache();

        return imagePath;
    }

    private static Bitmap loadBitmapFromView(View v) {
        int w = v.getWidth();
        int h = v.getHeight();
        Bitmap bmp = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
        Canvas c = new Canvas(bmp);
        c.drawColor(Color.WHITE);
        /** 如果不设置canvas画布为白色，则生成透明 */
        v.layout(0, 0, w, h);
        v.draw(c);
        return bmp;
    }


    /**
     * 以流的形式保存拍照的图片到指定文件夹
     *
     * @param inputStream 输入流
     * @param mImageName  要保存的文件名称
     */
    public static void saveImageFile(InputStream inputStream, String mImageName) {
        FileOutputStream fos = null;
        File imageFile = saveOutputMediaFile(mImageName);
        if (imageFile == null) {
            return;
        }

        if (inputStream == null) return;
        try {
            fos = new FileOutputStream(imageFile);
            byte[] buffer = new byte[1024];
            while (inputStream.read(buffer) != -1) {
                fos.write(buffer);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                assert fos != null;
                inputStream.close();
                fos.flush();
                fos.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 从sd卡获取图片资源路径
     *
     * @param fileDir 文件夹名称
     * @return 路径列表
     */
    public static List<String> getImagePathFromSD(String fileDir) {
        // 图片路径存储列表
        List<String> imagePathList = new ArrayList<>();
        // 得到该路径文件夹下所有的文件
        File[] files = getImageFiles(fileDir);
        // 将所有的文件存入ArrayList中,并过滤所有图片格式的文件
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            if (checkIsImageFile(file.getPath())) {
                imagePathList.add(file.getPath());
            }
        }
        // 返回得到的图片路径列表
        return imagePathList;
    }

    /**
     * 检查扩展名，得到图片格式的文件
     *
     * @param fName 文件名
     * @return
     */
    @SuppressLint("DefaultLocale")
    private static boolean checkIsImageFile(String fName) {
        boolean isImageFile;
        // 获取扩展名
        String FileEnd = fName.substring(fName.lastIndexOf(".") + 1,
                fName.length()).toLowerCase();
        if (FileEnd.equals("jpg") || FileEnd.equals("png") || FileEnd.equals("gif")
                || FileEnd.equals("jpeg") || FileEnd.equals("bmp")) {
            isImageFile = true;
        } else {
            isImageFile = false;
        }
        return isImageFile;
    }

    /**
     * 判断文件是否存在
     *
     * @param strFile 文件名
     * @return 布尔类型
     */
    public static boolean fileIsExists(String strFile) {
        try {
            File f = new File(strFile);
            if (!f.exists()) {
                return false;
            }

        } catch (Exception e) {
            return false;
        }

        return true;
    }

    /**
     * 格式化文件大小<b> 带有单位
     *
     * @param size
     * @return
     */
    public static String formatFileSize(long size) {
        StringBuilder sb = new StringBuilder();
        String u = null;
        double tmpSize = 0;
        if (size < KB) {
            sb.append(size).append("B");
            return sb.toString();
        } else if (size < MB) {
            tmpSize = getSize(size, KB);
            u = "KB";
        } else if (size < GB) {
            tmpSize = getSize(size, MB);
            u = "MB";
        } else {
            tmpSize = getSize(size, GB);
            u = "GB";
        }
        return sb.append(twodot(tmpSize)).append(u).toString();
    }

    /**
     * 保留两位小数
     *
     * @param d
     * @return
     */
    public static String twodot(double d) {
        return String.format("%.2f", d);
    }

    public static double getSize(long size, long u) {
        return (double) size / (double) u;
    }

    /**
     * 从流中读取文件
     *
     * @param is
     * @return
     * @throws IOException
     */
    public static String readTextInputStream(InputStream is) throws IOException {
        StringBuffer strbuffer = new StringBuffer();
        String line;
        BufferedReader reader = null;
        try {
            reader = new BufferedReader(new InputStreamReader(is));
            while ((line = reader.readLine()) != null) {
                strbuffer.append(line).append("\r\n");
            }
        } finally {
            if (reader != null) {
                reader.close();
            }
        }
        return strbuffer.toString();
    }

    /**
     * 获取一个文件夹大小
     *
     * @param f
     * @return
     * @throws Exception
     */
    public static long getFileSize(File f) {
        long size = 0;
        File flist[] = f.listFiles();
        for (int i = 0; i < flist.length; i++) {
            if (flist[i].isDirectory()) {
                size = size + getFileSize(flist[i]);
            } else {
                size = size + flist[i].length();
            }
        }
        return size;
    }

    public static String getRootFilePath() {
        if (hasSDCard()) {
            File file = new File(Environment.getExternalStorageDirectory()
                    .getAbsolutePath() + "/" + "SecureCheckPlatform" + "/");
            if (!file.exists()) {
                file.mkdirs();
            }
            return Environment.getExternalStorageDirectory().getAbsolutePath()
                    + "/" + "SecureCheckPlatform" + "/";
        } else {
            return Environment.getDataDirectory().getAbsolutePath() + "/data/"; // filePath:
        }
    }


    /**
     * 将文件转换成byte数组
     */
    public static byte[] File2byte(File tradeFile) {
        byte[] buffer = null;
        try {
            FileInputStream fis = new FileInputStream(tradeFile);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            byte[] b = new byte[1024];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer;
    }

}
